public without sharing class PerformanceRightsConfirmationController {
    
    public String msg {private set ;get;}
    public Boolean isSuccess {private set; get;}
    public String dataJson {private set; get;}
    public String saveJson {set;get;}
    public String combobox {get; private set;}
    public String provincesbox {get ; private set;}
    public String searchJson {get; set;}
    public Boolean isErr  {private set; get;}
    private Map<String,Object> rMap ; 

    private User u ;
    public PerformanceRightsConfirmationController() {
    	rMap = new Map<String,Object>();
    	u = [select Id,Name,Profile.Name  from User where Id=:UserInfo.getUserId() ];
    		getRight();
    }

    public void setNil(){
    	dataJson = '[]';
    	saveJson = '[]';
    	searchJson = '{}';

    }

    public void getRight(){
    	rMap = (Map<String,Object>)JSON.deserializeUntyped(Label.PerformanceRight);
    }
    public void init(){

    	try {

    	    if( !rMap.containsKey(u.Name) && u.Profile.Name != '系统管理员' ) new DmlException('没有权限操作!');

    	    getProvinceBox();
    	
        	combobox = JSON.serialize(ImportObject.getPicklistValues('PerformanceRightsConfirmation__c', 'Company__c', true)) ;

    	}catch (Exception e) {
    		isErr = true;
    	    ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));

    	    
    	}
    	

    }

    private void getProvinceBox(){

    	String whereStr = getWhereString();
    	String proviceSql = ' select Province__c from PerformanceRightsConfirmation__c where CreatedDate != null  '+whereStr +' Group by Province__c ' ;
    	

    	Map<String,String> ctmp = new Map<String,String>();
    	System.debug(proviceSql);

    	for(AggregateResult  arg  : Database.query(proviceSql)){

    		ctmp.put((String)arg.get('Province__c'), (String)arg.get('Province__c'));
    	}
    	System.debug('PerformanceRightsConfirmation__c==>'+ctmp);
    	provincesbox = JSON.serialize(ctmp);
    }
    private String getWhereString(){
    	String whereStr = '';
    	Object right = rMap.get(u.Name);
    	
    	if(right != null && right instanceof String){
    		
            whereStr = String.isBlank(String.valueOf(right)) ? ' ' : ' and  Company__c=\''+right+'\' ' ;

    	}
    	return whereStr;

    }
    public void getDetails(){
    	List<DetailBean> tmp = new List<DetailBean>();
    	Map<String,Object> searchMap = (Map<String,Object> ) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));
    	String sql = 'select Id,AccountName__c,Company__c,AccountType__c,TerminalAccount__r.Level__c,'+
    		' Province__c,TerminalAccountName__c,'+
            
            ' DirectBusinessOwner__c,DirectBusinessOwner__r.Name,DirectBusinessOwner__r.ExuserCode__c,'+
    		' DirectBusinessOwnerManager__c,DirectBusinessOwnerManager__r.Name,DirectBusinessOwnerManager__r.ExuserCode__c,'+
            
            ' DistributionOwner__c,DistributionOwner__r.Name,DistributionOwner__r.ExuserCode__c,'+
    		' DistributionOwnerManager__c,DistributionOwnerManager__r.Name,DistributionOwnerManager__r.ExuserCode__c,'+
            
            ' ProvinceManager__c,ProvinceManager__r.Name ,ProvinceManager__r.ExuserCode__c,'+

            ' TripartiteOwner__c,TripartiteOwner__r.Name,TripartiteOwner__r.ExuserCode__c,'+
    		' TripartiteOwnerManager__c,TripartiteOwnerManager__r.Name,TripartiteOwnerManager__r.ExuserCode__c ,'+

            ' BiochemicalIOwnerManager__c,BiochemicalIOwnerManager__r.Name ,BiochemicalIOwnerManager__r.ExuserCode__c,'+
            ' BiochemicalIOwner__c,BiochemicalIOwner__r.Name ,BiochemicalIOwner__r.ExuserCode__c,'+

            ' PathologyOwnerManager__c,PathologyOwnerManager__r.Name,PathologyOwnerManager__r.ExuserCode__c,'+
            ' PathologyOwner__c,PathologyOwner__r.Name ,PathologyOwner__r.ExuserCode__c,'+

            ' POCTOwnerManager__c,POCTOwnerManager__r.Name,POCTOwnerManager__r.ExuserCode__c,'+
            ' POCTOwner__c,POCTOwner__r.Name,POCTOwner__r.ExuserCode__c,'+

            ' ImmunityOwnerManager__c,ImmunityOwnerManager__r.Name,ImmunityOwnerManager__r.ExuserCode__c,'+
            ' ImmunityOwner__c,ImmunityOwner__r.Name ,ImmunityOwner__r.ExuserCode__c,'+
            
            ' SysmexOwner__c,SysmexOwner__r.Name, SysmexOwner__r.ExuserCode__c,'+
            ' SysmexOwnerManager__c,SysmexOwnerManager__r.Name, SysmexOwnerManager__r.ExuserCode__c,'+

            ' MicrobeOwner__c,MicrobeOwner__r.Name, MicrobeOwner__r.ExuserCode__c,'+
            ' MicrobeOwnerManager__c,MicrobeOwnerManager__r.Name, MicrobeOwnerManager__r.ExuserCode__c,'+

            ' MolecularOwner__c,MolecularOwner__r.Name,MolecularOwner__r.ExuserCode__c,'+
            ' MolecularOwnerManager__c,MolecularOwnerManager__r.Name,MolecularOwnerManager__r.ExuserCode__c,'+

            ' ClinicalLaboratoryOwner__c,ClinicalLaboratoryOwner__r.Name ,ClinicalLaboratoryOwner__r.ExuserCode__c,'+
            ' ClinicalLaboratoryOwnerManager__c,ClinicalLaboratoryOwnerManager__r.Name ,ClinicalLaboratoryOwnerManager__r.ExuserCode__c, '+

            ' BDOwnerManager__c,BDOwnerManager__r.Name,BDOwnerManager__r.ExuserCode__c,'+
            ' BDOwner__c,BDOwner__r.Name ,BDOwner__r.ExuserCode__c'+

    		' from PerformanceRightsConfirmation__c ';

    	String whereStr = getWhereString();


    	//3 4 5   6 7 8   9 10 11     12 1 2 
    	Integer currentM = System.today().month() ;

    	if(currentM <=5 && currentM >= 3 ) sql += ' where Quarter__c=\'1\' and Year__c =\''+(System.today().year())+'年'+'\' ';
    	if(currentM <=8 && currentM >= 6 ) sql += ' where Quarter__c=\'2\' and Year__c =\''+(System.today().year())+'年'+'\' ';
    	if(currentM <=11 && currentM >= 9 ) sql += ' where Quarter__c=\'3\' and Year__c =\''+(System.today().year())+'年'+'\' ';
    	if(currentM >= 12 && currentM <= 2 ) sql += ' where Quarter__c=\'4\' and Year__c =\''+(System.today().year()-1)+'年'+'\' ';

    	if(searchMap != null && !searchMap.isEmpty()){

    		if(! String.isBlank((String)searchMap.get('accName')) )sql  += ' and ( AccountName__c like \'%'+searchMap.get('accName')+ '%\'  or  Account__r.Name  like \'%'+searchMap.get('accName')+ '%\' )  ';
    	   	if(! String.isBlank((String)searchMap.get('terminalName')) )sql  += ' and  (TerminalAccountName__c like \'%'+searchMap.get('terminalName')+ '%\'  or TerminalAccount__r.Name like \'%'+searchMap.get('terminalName')+ '%\'  )  ';
    		if(! String.isBlank((String)searchMap.get('province')) )sql  += ' and  Province__c like \'%'+searchMap.get('province')+ '%\'';
    		//if(! String.isBlank((String)searchMap.get('accName')) )sql  += ' and  AccountName__c like \'%'+searchMap.get('accName')+ '%\'';

    	}

    	if(String.isBlank(whereStr) )whereStr = ' limit 2000 ';

    	System.debug(sql);
    	for(PerformanceRightsConfirmation__c rcl : Database.query(sql+whereStr) ){

    		tmp.add(new DetailBean(rcl));
    	}

    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }

    @RemoteAction
    public static  Map<String,UserBean> matchUser(List<String> users ){

    	Map<String,UserBean> tmp =new Map<String,UserBean>();
    	for(User u:[select Id,Name , ExuserCode__c from User where ExuserCode__c in: users and IsActive = true  ]){
    		tmp.put(u.ExuserCode__c, new UserBean(u));
    	}
    	return tmp;
    }

    public void save(){
    	msg = '';
    	try {
    		List<Object> saveList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

    		List<PerformanceRightsConfirmation__c> details = new List<PerformanceRightsConfirmation__c>();
    		for(Object o :saveList){
    			Map<String,Object> mo = (Map<String,Object>)o;
    			PerformanceRightsConfirmation__c rcl = new PerformanceRightsConfirmation__c();
    			rcl.Id = DataUtil.getStringValue(mo.get('detailId'));
    			if(String.isBlank(rcl.Id)){
    				msg = '数据Id为空,异常数据!';
    				return;
    			}
                rcl.ProvinceManager__c =  DataUtil.getStringValue(mo.get('provinceId'));

    			rcl.DistributionOwner__c =  DataUtil.getStringValue(mo.get('caterId'));
    			rcl.DistributionOwnerManager__c = DataUtil.getStringValue(mo.get('caterManagerId'));

    			rcl.DirectBusinessOwner__c = DataUtil.getStringValue(mo.get('salerId'));
    			rcl.DirectBusinessOwnerManager__c = DataUtil.getStringValue(mo.get('salerManagerId'));

    			rcl.TripartiteOwner__c = DataUtil.getStringValue(mo.get('thirdId'));
    			rcl.TripartiteOwnerManager__c = DataUtil.getStringValue(mo.get('thirdManagerId'));

                rcl.BiochemicalIOwner__c = DataUtil.getStringValue(mo.get('shId'));
                rcl.BiochemicalIOwnerManager__c = DataUtil.getStringValue(mo.get('shManagerId'));

                 rcl.ImmunityOwner__c = DataUtil.getStringValue(mo.get('myId'));
                rcl.ImmunityOwnerManager__c = DataUtil.getStringValue(mo.get('myManagerId'));

                 rcl.ClinicalLaboratoryOwner__c = DataUtil.getStringValue(mo.get('ljId'));
                rcl.ClinicalLaboratoryOwnerManager__c = DataUtil.getStringValue(mo.get('ljManagerId'));

                 rcl.PathologyOwner__c = DataUtil.getStringValue(mo.get('blId'));
                rcl.PathologyOwnerManager__c = DataUtil.getStringValue(mo.get('blManagerId'));

                rcl.POCTOwner__c = DataUtil.getStringValue(mo.get('poctId'));
                rcl.POCTOwnerManager__c = DataUtil.getStringValue(mo.get('poctManagerId'));

                rcl.SysmexOwner__c = DataUtil.getStringValue(mo.get('xsmkId'));
                rcl.SysmexOwnerManager__c = DataUtil.getStringValue(mo.get('xsmkManagerId'));

                rcl.MicrobeOwner__c = DataUtil.getStringValue(mo.get('wswId'));
                rcl.MicrobeOwnerManager__c = DataUtil.getStringValue(mo.get('wswManagerId'));

                rcl.BDOwnerManager__c =  DataUtil.getStringValue(mo.get('bdManagerId'));
                rcl.BDOwner__c =  DataUtil.getStringValue(mo.get('bdId'));

                rcl.MolecularOwnerManager__c = DataUtil.getStringValue(mo.get('fzManagerId'));
                rcl.MolecularOwner__c =  DataUtil.getStringValue(mo.get('fzId'));
                
    			details.add(rcl);
    		}

    		SavePoint sp = Database.setSavepoint();
    		try {
    		    if(!details.isEmpty())update details;
    		    isSuccess = true;
    		    msg = '保存成功!';
    		}
    		catch (Exception e) {
    		     msg ='保存失败:'+ e.getMessage() ;
    		}
    		
    	    
    	}

    	catch (Exception e) {
    	    msg ='保存失败:'+ e.getMessage() ;
    	}
    	

    }
     public class UserBean{
    	public String id;
    	public String name;
    	public String uno;
    	public UserBean(User u ){
    		id = u.Id;
    		name = u.Name;
    		uno = u.ExuserCode__c;
    	}
    }

    public class DetailBean{

    	public String detailId;

    	public String accName ; //开票客户

    	public String terminalName ;//终端客户
    	public String company ;//归口公司

    	public String province;//归口省份

    	//public String cate ;//产品线/产品大类
    	public String accType ;//开票客户类型
    	public String terminalLevel ; //开票客户等级

    	public String salerId ;//直销人员Id ;
    	public String salerName ;
    	public String salerno;

    	public String salerManagerId;//直销管理从员
    	public String salerManagerName;
    	public String salerMno;

    	public String caterId ;//分销人员
    	public String caterName;
		public String caterno;

    	public String caterManagerId;//分销管理人员
    	public String caterManagerName;
    	public String caterMno;
        
        public String provinceId;//省区管理人员
        public String provinceName;
        public String provinceno;
        

    	public String thirdId;//三方人员
    	public String thirdName ; 
    	public String thirdno;

    	public String thirdManagerId;
    	public String thirdManagerName;
    	public String thirdMno;

        public String shId ;
        public String shName;
        public String shno;

        public String shManagerId;
        public String shManagerName;
        public String shManagerno;

        public String myId ;
        public String myName;
        public String myno;

        public String myManagerId;
        public String myManagerName;
        public String myManagerno;

        public String ljId ;
        public String ljName;
        public String ljno;

        public String ljManagerId;
        public String ljManagerName;
        public String ljManagerno;

        public String blId ;
        public String blName;
        public String blno;

        public String blManagerId;
        public String blManagerName;
        public String blManagerno;

        public String poctId ;
        public String poctName;
        public String poctno;

        public String poctManagerId;
        public String poctManagerName;
        public String poctManagerno;

        public String xsmkId ;
        public String xsmkName;
        public String xsmkno;

        public String xsmkManagerId;
        public String xsmkManagerName;
        public String xsmkManagerno;

        public String wswId ;
        public String wswName;
        public String wswno;

        public String wswManagerId;
        public String wswManagerName;
        public String wswManagerno;

        public String bdId ;
        public String bdName;
        public String bdno;

        public String bdManagerId;
        public String bdManagerName;
        public String bdManagerno;


        public String fzId ; 
        public String fzName;
        public String fzno ; 

        public String fzManagerId;
        public String fzManagerName;
        public String fzManagerno;



    	public DetailBean(PerformanceRightsConfirmation__c rcl ){
    		//mainId = rcl.RightsConfirmation__c;
    		detailId = rcl.Id;

    		accName = rcl.AccountName__c;
    		accType = rcl.AccountType__c;
    		terminalLevel = rcl.TerminalAccount__r.Level__c;

    		province = rcl.Province__c;

    		terminalName = rcl.TerminalAccountName__c;
    		company = rcl.Company__c;
    		//cate = rcl.ProductTpye__c;

    		salerId = rcl.DirectBusinessOwner__c;
    		salerName = rcl.DirectBusinessOwner__r.Name;
            salerno = rcl.DirectBusinessOwner__r.ExuserCode__c;

    		salerManagerId = rcl.DirectBusinessOwnerManager__c;
    		salerManagerName = rcl.DirectBusinessOwnerManager__r.Name;
            salerMno = rcl.DirectBusinessOwnerManager__r.ExuserCode__c;

    		caterId = rcl.DistributionOwner__c;
    		caterName = rcl.DistributionOwner__r.Name;
            caterno = rcl.DistributionOwner__r.ExuserCode__c;

    		caterManagerId = rcl.DistributionOwnerManager__c;
    		caterManagerName = rcl.DistributionOwnerManager__r.Name;
            caterMno = rcl.DistributionOwnerManager__r.ExuserCode__c;

            provinceId = rcl.ProvinceManager__c;
            provinceName = rcl.ProvinceManager__r.Name;
            provinceno = rcl.ProvinceManager__r.ExuserCode__c;

    		thirdId = rcl.TripartiteOwner__c;
    		thirdName = rcl.TripartiteOwner__r.Name;
            thirdno = rcl.TripartiteOwner__r.ExuserCode__c;

    		thirdManagerId = rcl.TripartiteOwnerManager__c;
    		thirdManagerName = rcl.TripartiteOwnerManager__r.Name;
            thirdMno = rcl.TripartiteOwnerManager__r.ExuserCode__c;

            shId = rcl.BiochemicalIOwner__c;
            shName = rcl.BiochemicalIOwner__r.Name;
            shno = rcl.BiochemicalIOwner__r.ExuserCode__c;

            shManagerId = rcl.BiochemicalIOwnerManager__c;
            shManagerName = rcl.BiochemicalIOwnerManager__r.Name;
            shManagerno = rcl.BiochemicalIOwnerManager__r.ExuserCode__c;

            myId = rcl.ImmunityOwner__c;
            myName = rcl.ImmunityOwner__r.Name;
            myno = rcl.ImmunityOwner__r.ExuserCode__c;

            myManagerId = rcl.ImmunityOwnerManager__c;
            myManagerName = rcl.ImmunityOwnerManager__r.Name;
            myManagerno = rcl.ImmunityOwnerManager__r.ExuserCode__c;

            ljId = rcl.ClinicalLaboratoryOwner__c;
            ljName = rcl.ClinicalLaboratoryOwner__r.Name;
            ljno = rcl.ClinicalLaboratoryOwner__r.ExuserCode__c;

            ljManagerId = rcl.ClinicalLaboratoryOwnerManager__c;
            ljManagerName = rcl.ClinicalLaboratoryOwnerManager__r.Name;
            ljManagerno = rcl.ClinicalLaboratoryOwnerManager__r.ExuserCode__c;

            blId = rcl.PathologyOwner__c;
            blName = rcl.PathologyOwner__r.Name;
            blno = rcl.PathologyOwner__r.ExuserCode__c;

            blManagerId = rcl.PathologyOwnerManager__c;
            blManagerName = rcl.PathologyOwnerManager__r.Name;
            blManagerno = rcl.PathologyOwnerManager__r.ExuserCode__c;

            poctId = rcl.POCTOwner__c;
            poctName = rcl.POCTOwner__r.Name;
            poctno = rcl.POCTOwner__r.ExuserCode__c;

            poctManagerId = rcl.POCTOwnerManager__c;
            poctManagerName = rcl.POCTOwnerManager__r.Name;
            poctManagerno = rcl.POCTOwnerManager__r.ExuserCode__c;


            xsmkId = rcl.SysmexOwner__c;
            xsmkName = rcl.SysmexOwner__r.Name;
            xsmkno = rcl.SysmexOwner__r.ExuserCode__c;

            xsmkManagerId = rcl.SysmexOwnerManager__c;
            xsmkManagerName = rcl.SysmexOwnerManager__r.Name;
            xsmkManagerno = rcl.SysmexOwnerManager__r.ExuserCode__c;

            wswId = rcl.MicrobeOwner__c;
            wswName = rcl.MicrobeOwner__r.Name;
            wswno = rcl.MicrobeOwner__r.ExuserCode__c;

            wswManagerId = rcl.MicrobeOwnerManager__c;
            wswManagerName = rcl.MicrobeOwnerManager__r.Name;
            wswManagerno = rcl.MicrobeOwnerManager__r.ExuserCode__c;

            bdId = rcl.BDOwner__c;
            bdno = rcl.BDOwner__r.ExuserCode__c;
            bdName = rcl.BDOwner__r.Name;

            bdManagerId = rcl.BDOwnerManager__c;
            bdManagerName = rcl.BDOwnerManager__r.Name;
            bdManagerno = rcl.BDOwnerManager__r.ExuserCode__c;

            fzId = rcl.MolecularOwner__c;
            fzno = rcl.MolecularOwner__r.ExuserCode__c;
            fzName = rcl.MolecularOwner__r.Name;

            fzManagerId = rcl.MolecularOwnerManager__c;
            fzManagerName = rcl.MolecularOwnerManager__r.Name;
            fzManagerno = rcl.MolecularOwnerManager__r.ExuserCode__c;

    	}

    }
}